﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace PMS.Controllers.BD
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult UserList()
        {
            return View();
        }
        public ActionResult AssignComboPeoWindow()
        {
            return View();
        }
        public ActionResult AssignComboPeoWindowBySchool()
        {
            return View();
        }
        public ActionResult ChangePwdWindow()
        {
            return View();
        }
        public ActionResult ChangeLoginName()
        {
            return View();
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        public void GetUserList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
            }
            listSearch.Add(new SearchCondition() { Field = "UserState",Operator="=" ,Value="0"});
            Expression<Func<View_BD_UserDepInfo, bool>> exp = SearchExpression.FindByGroup<View_BD_UserDepInfo>(listSearch);
            int count = 0;
            var list = BLLSession.Current.View_BD_UserDepInfoBLL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, u => u.ID, OperateContext.Order);
            var userIdList = list.Select(s => s.ID).ToList();
            var userRole = DALSession.Current.BD_UserRoleDAL.GetListBy(r => userIdList.Contains(r.UId)).ToList();
            var roleIdList = userRole.Select(r => r.RId).ToList();
            var roleList = DALSession.Current.BD_RoleDAL.GetListBy(r => roleIdList.Contains(r.Id)).ToList();
            foreach (var item in list)
            {
                var userRoleIdList = userRole.Where(r => r.UId == item.ID).Select(r => r.RId).ToList();
                var RoleNameList = roleList.Where(r => userRoleIdList.Contains(r.Id)).ToList();
                string roleName = "";
                foreach (var roleNameItem in RoleNameList)
                {
                    roleName += roleNameItem.Name + ",";
                }
                string a = roleName.TrimEnd(',');
                item.RoleName = a;
            }
            count = BLLSession.Current.View_BD_UserDepInfoBLL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }
        /// <summary>
        /// 根据q获取人员信息
        /// </summary>
        //public void GetClassUserInfoByQ()
        //{
        //    string q = Request.Form["q"];
        //    int intQ = Commons.String2Int32(q);
        //    var a = DALSession.Current.View_BD_UserDepInfoDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, m => (m.ID == intQ || m.UserName.Contains(q) || m.DepName.Contains(q)), "ID", OperateContext.OrderDesc).Select(m => new { value = m.ID, text = m.UserName, DepName = m.DepName, DepId = m.DepId, UserState = m.UserState });
        //    int count = DALSession.Current.View_BD_UserDepInfoDAL.GetCount(m => (m.ID == intQ || m.UserName.Contains(q) || m.DepName.Contains(q)));
        //    Response.Write(JsonHelper.toPageJson(a, count));
        //    //&& m.FatherId == 4,, && m.FatherId == 4
        //}
        public ActionResult UserDetail()
        {
            return View();
        }
        ///新增/查看/编辑时获取人员信息
        public void getUserDetail()
        {
            int Id = Commons.String2Int32(Request["ID"].ToString());
            var mainUser = DALSession.Current.BD_UserInfoDAL.GetListBy(p => p.ID == Id).FirstOrDefault();
            var detailXueli = DALSession.Current.BD_UserEducationDAL.GetListBy(p => p.StaffInfoId == Id).ToList();
            var detailWork = DALSession.Current.BD_UserWorkHistoryDAL.GetListBy(p => p.StaffInfoId == Id).ToList();
            var detailFamily = DALSession.Current.BD_UserFamilyDAL.GetListBy(p => p.UserId == Id).ToList();
            Response.Write(JsonHelper.toJson(new { mainUser = mainUser, detailXueli = detailXueli, detailWork = detailWork, detailFamily = detailFamily }));
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        public void EditUser()
        {
            int ID = Commons.String2Int32(Request.Form["ID"]);
            BD_UserInfo perNew = BLLSession.Current.BD_UserInfoBLL.GetListBy(d => d.ID == ID).FirstOrDefault();
            ModelTools.Form2EditModel(Request.Form, perNew);

            perNew.SchoolCode = Request.Form["SchoolCode"].ToString().Trim();
            BD_SchoolInfo SchoolInfo = DALSession.Current.BD_SchoolInfoDAL.GetListBy(c => c.SchoolCode == perNew.SchoolCode).FirstOrDefault();
            perNew.SchoolName = SchoolInfo.SchoolName;
            perNew.ManClerk = OperateContext.sessUserInfo.Name;
            perNew.FillDate = DateTime.Now.ToString("yyyy:MM:dd,HH:mm:ss");
            BLLSession.Current.BD_UserInfoBLL.ModifyAllModel(perNew);
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }
        /// <summary>
        /// 初始添加用户信息
        /// </summary>
        public void AddUser()
        {
            string Code = "";
            string y = DateTime.Now.Year.ToString();
            string code = DALSession.Current.BD_UserInfoDAL.GetListBy(i => i.UserCode.Substring(0, 4) == y, p => p.UserCode, false).Select(p => p.UserCode).FirstOrDefault();
            if (code == null)
            {
                Code = y + "0001";
            }
            else
            {
                int code1 = Commons.String2Int32(code.Substring(4, 4));
                code1 += 1;
                Code = Convert.ToString(code1);
                Code = Code.PadLeft(4, '0');
                Code = y + Code;
            }
            BD_UserInfo per = new BD_UserInfo() { ManClerk = OperateContext.sessUserInfo.Name, FillDate = DateTime.Now.ToString("yyyy-MM-dd"), AccountLogIn = Code, UserCode = Code, PassWord = "123456", UserState = "0", SchoolCode = OperateContext.sessUserInfo.SchoolCode, SchoolName = OperateContext.sessUserInfo.SchoolName, BirthDate = DateTime.Now.ToString("yyyy-MM-dd"), MinZu = "汉族", Sex = "0", IfMarry = "0" };
            int ID = Commons.String2Int32(DALSession.Current.BD_UserInfoDAL.AddModelReturnId(per, "ID"));
            BD_UserEducation edu = new BD_UserEducation() { StaffInfoId = ID, StaffCode = Code, EduStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"), EduEndtDate = DateTime.Now.ToString("yyyy-MM-dd") };
            BLLSession.Current.BD_UserEducationBLL.Add(edu);
            BLLSession.Current.BD_UserEducationBLL.Add(edu);
            BLLSession.Current.BD_UserEducationBLL.Add(edu);
            BD_UserFamily fam = new BD_UserFamily() { UserId = ID, UserCode = Code };
            BLLSession.Current.BD_UserFamilyBLL.Add(fam);
            BLLSession.Current.BD_UserFamilyBLL.Add(fam);
            BD_UserWorkHistory work = new BD_UserWorkHistory() { StaffInfoId = ID, StaffCode = Code, WorkStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"), WorkEndtDate = DateTime.Now.ToString("yyyy-MM-dd") };
            BLLSession.Current.BD_UserWorkHistoryBLL.Add(work);
            BLLSession.Current.BD_UserWorkHistoryBLL.Add(work);
            BLLSession.Current.BD_UserWorkHistoryBLL.Add(work);
            Response.Write(JsonHelper.toJson(new { ID = ID, state = "success" }));
        }

        //新增用户明细
        public ActionResult AddEditUserDetail(int ID, BD_UserInfo user, string xueli, string work, string family)
        {
            //int ID = Commons.String2Int32(Request["Id"].ToString());
            string action = Request["action"].ToString();
            //string[] ma = Request.Form["main"].Split(',');
            string Id = user.IdNumber;
            string name = user.UserName;
            List<BD_UserInfo> list = DALSession.Current.BD_UserInfoDAL.GetListBy(p => p.UserName == name && p.IdNumber == Id).ToList();
            if (action == "add" && list.Count > 1)
            {
                return Json(new { state = "success", msg = "身份证号+姓名重复，请重新核实！！" });
            }
            else
            {
                user.ID = ID;
                List<BD_UserEducation> xueliList = JsonConvert.DeserializeObject<List<BD_UserEducation>>(xueli);
                List<BD_UserWorkHistory> workList = JsonConvert.DeserializeObject<List<BD_UserWorkHistory>>(work);
                List<BD_UserFamily> familyList = JsonConvert.DeserializeObject<List<BD_UserFamily>>(family);
                Message msg = BLLSession.Current.BD_UserInfoBLL.EditUserDetail(user, xueliList, workList, familyList);
                return Json(msg);
            }

            //BD_UserInfo mainInfo = new BD_UserInfo();
            //mainInfo.DepName = ma[0];
            //mainInfo.DepId = Commons.String2Int32(ma[1]);
            //mainInfo.PosName = ma[2];
            //mainInfo.PosId = Commons.String2Int32(ma[3]);
            //mainInfo.SchoolName = ma[4];
            //mainInfo.SchoolCode = ma[5];
            //mainInfo.Sex = ma[6];
            //mainInfo.IfMarry = ma[7];
            //mainInfo.BirthDate = ma[8];
            //mainInfo.UserName = ma[9];
            //mainInfo.MinZu = ma[10];
            //mainInfo.Huji = ma[11];
            //mainInfo.IdNumber = ma[12];
            //mainInfo.Address = ma[13];
            //mainInfo.Phone = ma[14];
            //mainInfo.E_Mail = ma[15];
            //mainInfo.Univeristy = ma[16];
            //mainInfo.Major = ma[17];
            //mainInfo.Note = ma[18];
            //mainInfo.ApplySalary = ma[19];
            //mainInfo.UserName = ma[20];
            //mainInfo.UserCode = ma[21];
            //DALSession.Current.BD_UserInfoDAL.ModifyBy(mainInfo, p => p.ID == ID, "DepName ", "DepId ", " PosName ", " PosId ", " SchoolName ", " SchoolCode ", " Sex ", " IfMarry ", " BirthDate ", " UserName ", " MinZu ", " Huji ", " IdNumber ", " Address ", " Phone ", " E_Mail ", " Univeristy ", " Major ", " Note ", " ApplySalary", "UserName");
            //DALSession.Current.BD_UserEducationDAL.DelBy(e => e.StaffInfoId == ID);

        }
        /// <summary>
        /// 删除用户信息
        /// </summary>
        public void DelUser()
        {
            //  int Id = Commons.String2Int32(Request.Form["Id"]);
            int Id = Convert.ToInt32(Request.Form["Id"].ToString());
            BD_UserInfo user = DALSession.Current.BD_UserInfoDAL.GetListBy(u => u.ID == Id).FirstOrDefault();
            user.UserState = "1";
            BLLSession.Current.BD_UserInfoBLL.ModifyBy(user, t => t.ID == user.ID, "UserState");
            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }
        /// <summary>
        /// 获取用户角色
        /// </summary>
        public void GetUserRole()
        {
            int userId = Convert.ToInt32(Request.Form["Id"]);
            List<BD_Role> roleList = Permission.GetAllRole(userId);
            List<int> roleIdList = BLLSession.Current.BD_UserRoleBLL.GetListBy(p => p.UId == userId).Select(u => u.RId).ToList();
            List<CheckboxList> cblist = new List<CheckboxList>();
            foreach (var item in roleList)
            {
                if (roleIdList.Contains(item.Id))
                {
                    cblist.Add(new CheckboxList() { value = item.Id.ToString(), text = item.Name, Checked = true });
                }
                else
                {
                    cblist.Add(new CheckboxList() { value = item.Id.ToString(), text = item.Name, Checked = false });
                }
            }
            Response.Write(JsonHelper.toJson(cblist));
        }
        /// <summary>
        /// 修改用户角色
        /// </summary>
        public void EditUserRole()
        {
            int userId = Convert.ToInt32(Request.Form["Id"]);
            List<int> checkrole = new List<int>();
            string roleids = Request.Form["RoleIds"].ToString();
            for (int i = 0; i < roleids.Trim(',').Split(',').Length; i++)
            {
                checkrole.Add(Commons.String2Int32(roleids.Trim(',').Split(',')[i]));
            }
            BLLSession.Current.BD_UserRoleBLL.DelBy(p => p.UId == userId);
            foreach (var urId in checkrole)
            {
                BLLSession.Current.BD_UserRoleBLL.Add(new BD_UserRole() { RId = urId, UId = userId });
            }
            Response.Write(JsonHelper.toDefaultMsg(true));

        }
        /// <summary>
        /// 获取用户页面链接特权
        /// </summary>
        //public void GetUserLinkTree()
        //{
        //    int userId = Convert.ToInt32(Request.Form["Id"]);
        //    List<BD_Permission> perm = Permission.GetAllLink();
        //    List<BD_UserVipPermission> userPerm = Permission.GetPermByUserid(userId);
        //    List<TreeNode> node = Permission.GetPerTreeBySubTreeUserid(perm, userPerm);
        //    string nodeStr = JsonHelper.toJson(node);
        //    string newNodeStr = nodeStr.Replace("Checked", "checked");
        //    Response.Write(JsonHelper.toJson(newNodeStr));
        //}
        ///// <summary>
        ///// 修改用户页面链接特权
        ///// </summary>
        //public void EditUserLinkTree()
        //{
        //    int userId = Convert.ToInt32(Request.Form["Id"]);
        //    List<int> nodes = new List<int>();
        //    string nodesStr = Request.Form["PermIds"].ToString();
        //    for (int i = 0; i < nodesStr.Trim(',').Split(',').Length; i++)
        //    {
        //        nodes.Add(Commons.String2Int32(nodesStr.Trim(',').Split(',')[i]));
        //    }
        //    DALSession.Current.BD_UserVipPermissionDAL.DelBy(p => p.vipUserId == userId);
        //    foreach (var pId in nodes)
        //    {
        //        DALSession.Current.BD_UserVipPermissionDAL.Add(new BD_UserVipPermission() { vipPermission = pId, vipUserId = userId });
        //    }
        //    DALSession.Current.BD_UserVipPermissionDAL.SaveChanges();
        //    Response.Write(JsonHelper.toDefaultMsg(true));

        //}
        ////获取用户的权限按钮的树节点
        //public void GetUserBtnPer()
        //{
        //    //获取用户的ID
        //    int userId = Convert.ToInt32(Request.Form["Id"]);
        //    //获取用户的所有二级页面
        //    List<BD_Permission> UserPerm = Permission.GetPermByUserEr(userId);
        //    //获取该用户选中的按钮Id集合
        //    List<int> userBtnPerm = Permission.GetBtnPermIdListByUserid(userId);
        //    //获取用户所有二级页面下的按钮
        //    List<BD_btnPermission> allBtnPerm = Permission.GetAllBtnPermUser(UserPerm);
        //    //创建树节点
        //    List<TreeNode> node = Permission.GetBtnTreeUser(UserPerm, allBtnPerm, userBtnPerm);
        //    string nodeStr = JsonHelper.toJson(node).Replace("Checked", "checked");
        //    Response.Write(nodeStr);
        //}
        ////更改用户的权限按钮的树节点
        //public void EditUserBtnPer()
        //{
        //    //获取用户的ID
        //    int userId = Convert.ToInt32(Request.Form["Id"]);
        //    List<int> nodes = new List<int>();
        //    string nodesStr = Request.Form["PermIds"].ToString();
        //    for (int i = 0; i < nodesStr.Trim(',').Split(',').Length; i++)
        //    {
        //        nodes.Add(Commons.String2Int32(nodesStr.Trim(',').Split(',')[i]));
        //    }
        //    DALSession.Current.BD_UserVipBtnPermissionDAL.DelBy(p => p.vipUserId == userId);
        //    foreach (var PId in nodes)
        //    {
        //        DALSession.Current.BD_UserVipBtnPermissionDAL.Add(new BD_UserVipBtnPermission() { vipUserId = userId, vipBtnPermission = PId });
        //    }
        //    DALSession.Current.BD_UserVipBtnPermissionDAL.SaveChanges();
        //    Response.Write(JsonHelper.toDefaultMsg(true));
        //}
        //// 获取快捷登录列表
        //public void GetShortCutList()
        //{
        //    //获取所有快捷登录权限
        //    //  List<BD_Permission> perm = DALSession.Current.BD_PermissionDAL.GetListBy(p => p.IsShortCut == "0").ToList();
        //    List<BD_Permission> perm = OperateContext.SessPermission.Where(p => p.IsShortCut == "0").ToList();
        //    //获取本人快捷登录权限
        //    List<BD_Permission> mePerm = Permission.GetShortCutByMe();
        //    List<int> meIntList = mePerm.Select(m => m.Id).ToList();
        //    List<CheckboxList> cblist = new List<CheckboxList>();
        //    foreach (var item in perm)
        //    {
        //        if (meIntList.Contains(item.Id))
        //        {
        //            cblist.Add(new CheckboxList() { value = item.Id.ToString(), text = item.Name, Checked = true });
        //        }
        //        else
        //        {
        //            cblist.Add(new CheckboxList() { value = item.Id.ToString(), text = item.Name, Checked = false });
        //        }
        //    }

        //    Response.Write(JsonHelper.toJson(cblist));
        //}
        ///// <summary>
        ///// 编辑个人快速导航菜单
        ///// </summary>
        //public void EditShortCut()
        //{
        //    int userId = OperateContext.SessBasicInfo.UserInfo.Id;
        //    List<int> checkrole = new List<int>();
        //    string shortIds = Request.Form["ShortIds"].ToString();
        //    for (int i = 0; i < shortIds.Trim(',').Split(',').Length; i++)
        //    {
        //        checkrole.Add(Commons.String2Int32(shortIds.Trim(',').Split(',')[i]));
        //    }
        //    DALSession.Current.BD_UserShortCutDAL.DelBy(u => u.uId == userId);
        //    foreach (var urId in checkrole)
        //    {
        //        DALSession.Current.BD_UserShortCutDAL.Add(new BD_UserShortCut() { pId = urId, uId = userId });
        //    }
        //    DALSession.Current.BD_UserShortCutDAL.SaveChanges();
        //    Response.Write(JsonHelper.toDefaultMsg(true));
        //}








        ///// <summary>
        ///// 获取我的授权信息列表
        ///// </summary>
        //public void GetPerAuthorList()
        //{

        //    int userId = OperateContext.SessBasicInfo.UserInfo.Id;
        //    int count = 0;
        //    var list = DALSession.Current.View_BD_AuthorizeInfoDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, a => a.FromUserId == userId || a.ToUserId == userId, "FillDate", OperateContext.OrderDesc);
        //    count = DALSession.Current.View_BD_AuthorizeInfoDAL.GetCount(a => a.FromUserId == userId || a.ToUserId == userId);
        //    Response.Write(JsonHelper.toPageJson(list, count));
        //}



        //public void GetAuthorList()
        //{
        //    List<SearchCondition> listSearch = new List<SearchCondition>();
        //    string nowDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        //    if (Request.Form["searchData"] != null)
        //    {
        //        string searchData = Request.Form["searchData"];
        //        listSearch = ModelTools.GetSearchContions(searchData);
        //        if (listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault() != null)
        //        {
        //            listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault().Field = "FillDate";
        //        }
        //        if (listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault() != null)
        //        {
        //            listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault().Field = "FillDate";
        //        }
        //        if (listSearch.Where(s => s.Field == "AuthState").FirstOrDefault() != null)
        //        {
        //            if (listSearch.Where(s => s.Field == "AuthState").FirstOrDefault().Value == "0")
        //            {
        //                listSearch.Add(new SearchCondition() { Field = "StartTime", Operator = "str<=", Value = nowDate });
        //                listSearch.Add(new SearchCondition() { Field = "EndTime", Operator = "str>=", Value = nowDate });
        //            }
        //            else if (listSearch.Where(s => s.Field == "AuthState").FirstOrDefault().Value == "1")
        //            {
        //                listSearch.Add(new SearchCondition() { Field = "EndTime", Operator = "str<=", Value = nowDate });
        //            }
        //            else if (listSearch.Where(s => s.Field == "AuthState").FirstOrDefault().Value == "2")
        //            {
        //                listSearch.Add(new SearchCondition() { Field = "StartTime", Operator = "str>=", Value = nowDate });
        //            }
        //        }

        //    }
        //    Expression<Func<View_BD_AuthorizeInfo, bool>> exp = SearchExpression.FindByGroup<View_BD_AuthorizeInfo>(listSearch);
        //    string OrderId = OperateContext.Sort == null ? "FillDate" : OperateContext.Sort;
        //    int count = 0;
        //    var list = DALSession.Current.View_BD_AuthorizeInfoDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OperateContext.OrderDesc);
        //    count = DALSession.Current.View_BD_AuthorizeInfoDAL.GetCount(exp);
        //    Response.Write(JsonHelper.toPageJson(list, count));
        //}

        //public void GetAuthorOperList()
        //{
        //    List<SearchCondition> listSearch = new List<SearchCondition>();
        //    string nowDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        //    if (Request.Form["searchData"] != null)
        //    {
        //        string searchData = Request.Form["searchData"];
        //        listSearch = ModelTools.GetSearchContions(searchData);
        //        if (listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault() != null)
        //        {
        //            listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault().Field = "FillDate";
        //        }
        //        if (listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault() != null)
        //        {
        //            listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault().Field = "FillDate";
        //        }
        //    }
        //    Expression<Func<View_BD_AuthorizeOperInfo, bool>> exp = SearchExpression.FindByGroup<View_BD_AuthorizeOperInfo>(listSearch);
        //    string OrderId = OperateContext.Sort == null ? "FillDate" : OperateContext.Sort;
        //    int count = 0;
        //    var list = DALSession.Current.View_BD_AuthorizeOperInfoDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OperateContext.OrderDesc);
        //    count = DALSession.Current.View_BD_AuthorizeOperInfoDAL.GetCount(exp);
        //    Response.Write(JsonHelper.toPageJson(list, count));

        //}

        //combobox获取人员信息时的模糊匹配
        public void GetUserInfo()
        {
            string q = Request.Form["q"];
            List<BD_UserInfo> useList = new List<BD_UserInfo>() { };
            if (q != null)
            {
                useList = DALSession.Current.BD_UserInfoDAL.GetListBy(p =>p.UserState=="0"&&(p.UserName.Contains(q) || p.UserCode.Contains(q))).ToList();
            }
            else
            {
                useList = DALSession.Current.BD_UserInfoDAL.GetListBy(p => p.UserState == "0").ToList();
            }
            var a = useList.Select(p => new { UserName = p.UserName, UserCode = p.UserCode, ID = p.ID, DepId = p.DepId, DepName = p.DepName, PosId = p.PosId, PosName = p.PosName, inDate = p.FillDate }).ToList();
            Response.Write(JsonHelper.toJson(a));
        }
        //前台获取登录员工信息
        public void getUser()
        {
            int id = OperateContext.sessUserInfo.Id;
            Response.Write(JsonHelper.toJson(DALSession.Current.BD_UserInfoDAL.GetListBy(p => p.ID == id).FirstOrDefault()));
        }
        //非最底层校区人员登录后切换校区查询
        public void ChangeSchool()
        {
            int schoolid = int.Parse(Request.Form["schoolid"]);
            BD_SchoolInfo school = DALSession.Current.BD_SchoolInfoDAL.GetListBy(u => u.ID == schoolid).FirstOrDefault();
            if (school != null)
            {
                string newschoolcode = school.SchoolCode;
                string newschoolname = school.SchoolName;
                UserInfo user = (UserInfo)System.Web.HttpContext.Current.Session[OperateContext.InfoKey];
                if (newschoolcode != user.SchoolCodeQuery)
                {
                    user.SchoolCodeQuery = newschoolcode;
                    user.SchoolNameQuery = newschoolname;
                    List<string> allcodes = new List<string>();
                    List<BD_SchoolInfo> alllist = BLLSession.Current.BD_SchoolInfoBLL.GetListBy();
                    getAllChildCode(allcodes, newschoolcode, alllist);
                    string codes = "";
                    for (int i = 0; i < allcodes.Count; i++)
                    {
                        codes = codes + "," + allcodes[i];
                    }
                    if (codes.Length > 0)
                    {
                        codes = codes.Substring(1, codes.Length - 1);
                    }
                    user.SchoolCodeAll = codes;
                    System.Web.HttpContext.Current.Session[OperateContext.InfoKey] = user;
                    //2.1.2将用户id加密成字符串
                    string strCookieValue = SecurityHelper.EncryptUserInfo(user.Id.ToString());
                    //2.1.3创建cookie
                    HttpCookie cookie = new HttpCookie(OperateContext.InfoKey, strCookieValue);
                    cookie.Expires = DateTime.Now.AddDays(1);
                    System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                }
            }
            Response.Write(JsonHelper.toDefaultMsg(true));
        }
        private void getAllChildCode(List<string> list, string code, List<BD_SchoolInfo> allschools)
        {
            BD_SchoolInfo info = allschools.Where(u => u.SchoolCode == code).FirstOrDefault();
            list.Add(info.SchoolCode);
            List<string> sch = allschools.Where(u => u.ParentId == info.ID).Select(u => u.SchoolCode).ToList();
            for (int i = 0; i < sch.Count; i++)
            {
                getAllChildCode(list, sch[i], allschools);
            }
        }
        public void getSchoolCodeQuery()
        {
            UserInfo user = (UserInfo)System.Web.HttpContext.Current.Session[OperateContext.InfoKey];
            Response.Write(JsonHelper.toDefaultMsg(true, user.SchoolCodeQuery));
        }
        public void getSchoolIDQuery()
        {
            UserInfo user = (UserInfo)System.Web.HttpContext.Current.Session[OperateContext.InfoKey];
            BD_SchoolInfo school = DALSession.Current.BD_SchoolInfoDAL.GetListBy(u => u.SchoolCode == user.SchoolCodeQuery).FirstOrDefault();
            Response.Write(JsonHelper.toDefaultMsg(true, school.ID.ToString()));
        }


        public void ChangePwd()
        {
            string oldpwd = Request.Form["oldpwd"];
            string newpwd = Request.Form["newpwd"];
            int id = OperateContext.sessUserInfo.Id;
            BD_UserInfo info = DALSession.Current.BD_UserInfoDAL.GetListBy(u => u.ID == id && u.PassWord == oldpwd).FirstOrDefault();
            if (info == null)
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "原始密码错误！"));
            }
            else
            {
                info.PassWord = newpwd;
                BLLSession.Current.BD_UserInfoBLL.ModifyAllModel(info);
                Response.Write(JsonHelper.toDefaultMsg(true, "密码修改成功！"));
            }
        }
        public void ChangeLoginN()
        {
            string loginname = Request.Form["loginname"];

            BD_UserInfo info = DALSession.Current.BD_UserInfoDAL.GetListBy(u => u.LoginName == loginname).FirstOrDefault();
            if (info != null)
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "登录名已被使用！"));
            }
            else
            {
                int id = OperateContext.sessUserInfo.Id;
                info = DALSession.Current.BD_UserInfoDAL.GetListBy(u => u.ID == id).FirstOrDefault();
                info.LoginName = loginname;
                BLLSession.Current.BD_UserInfoBLL.ModifyAllModel(info);
                Response.Write(JsonHelper.toDefaultMsg(true, "修改成功！"));
            }
        }
        public void getCurrentName()
        {
            int id = OperateContext.sessUserInfo.Id;
            BD_UserInfo info = DALSession.Current.BD_UserInfoDAL.GetListBy(u => u.ID == id).FirstOrDefault();
            Response.Write(JsonHelper.toDefaultMsg(true, info.LoginName == null ? "" : info.LoginName));
        }
        public void ResetPassword()
        {
            int id = int.Parse(Request.Form["Id"]);
            BD_UserInfo info = DALSession.Current.BD_UserInfoDAL.GetListBy(u => u.ID == id ).FirstOrDefault();
            info.PassWord = "123456";
            BLLSession.Current.BD_UserInfoBLL.ModifyAllModel(info);
            Response.Write(JsonHelper.toDefaultMsg(true, "密码重置成功！"));
        }
    }
}